#!/usr/bin/python
# -*- coding: UTF-8 -*-

import tdli2_default as tdli2_def
import os, sys, string
from lxml import etree

def create_body(field, fp):
    strName = field.get('name')
    strType = field.get('type')
    strLength = field.get('length')

    fp.write(' '*4*3 + '<data>'+ '\n')
    fp.write(' '*4*4 + '<title></title>' + '\n')
    fp.write(' '*4*4 + '<variable>' + strName   + '</variable>' + '\n')
    if strType.strip()[0] == 'C':
        fp.write(' '*4*4 + '<justify>'  + 'Left' + '</justify>'  + '\n')
    else :
        fp.write(' '*4*4 + '<justify>'  + 'Right' + '</justify>'  + '\n')

    fp.write(' '*4*4 + '<length>'   + strLength + '</length>'   + '\n')
    fp.write(' '*4*3 + '</data>' + '\n')
    fp.write(' '*4*3 + '<space>1</space>' + '\n\n')

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print "Usage: pragname datxml-Failname"
        sys.exit()

    try:
        fp_data = open(os.environ['APPHOME'] + '%srpt%sdataxml%s' % (os.sep, os.sep, os.sep) + sys.argv[1], "r")
    except:
        print "open xml failed";
        sys.exit()

    try:
        fp_rpt = open(os.environ['APPHOME'] + '%srpt%srptxml%s' % (os.sep, os.sep, os.sep) + sys.argv[1], "w+")
    except:
        print "open xml failed";
        sys.exit()

    fp_rpt.write(tdli2_def.tdli2_head())

    fp_rpt.write('\n')
    fp_rpt.write(' '*4*1 + '<body showmode=\"1\">' + '\n')
    fp_rpt.write(' '*4*2 + '<detail>' + '\n')
    fields = etree.parse(fp_data).xpath('.//record[@type=$detail]/field', detail = 'Detail')
    for field in fields:
        create_body(field, fp_rpt)
    fp_rpt.write(' '*4*2 + '</detail>' + '\n')
    fp_rpt.write(' '*4*1 + '</body>' + '\n')

    fp_rpt.write(tdli2_def.tdli2_tail())
    fp_data.close()
    fp_rpt.close()

